<template>
  <table-pinel
      title="{{title}}"
      class="table-page-container"
      :model.sync="searchParams"
      :searchConfig="searchConfig"
      :pageNum.sync="pageSearchParams.pageNum"
      :pageSize.sync="searchParams.pageSize"
      :total="pageSearchParams.total"
      @search="search"
      @reset="reset"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  >
    <template v-slot:action>
      <!--表格右上角操作按钮-->
      <el-button type="primary" @click="create">添加</el-button>
      <!--      <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
    </template>

    <template v-slot:default="{ height }">
      <!--  表格内容 -->
      <el-table class="common-table" stripe border :data="tableData" :height="height"
        {{#if isShowDetail}}
                @row-dblclick="detail"
        {{/if}}
                @selection-change="handleSelectionChange" v-if="height">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" align="center" width="60"/>
        <el-table-column label="用户ID" prop="userId" align="center" min-width="100" show-overflow-tooltip/>
        <el-table-column label="操作" align="center" fixed="right" width="120">
          <template v-slot="{ row }">
            <el-link type="primary" @click="edit(row)">编辑</el-link>
            <!--            <el-link type="warning" @click="detail(row)">查看</el-link>-->
            <el-link type="danger" @click="del(row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialogs">
        <!-- 添加/修改/查看用户信息对话框 -->
        <component
            is="EditFormModal"
            :width="1000"
            label-width="100px"
            :title="title"
            :formData="formData"
            :rules="rules"
            :formItemConfig="formItemConfig"
            :api="api"
            :disabled="type === 2"
            @success="onSuccess"
            ref="modalEdit"
        >
          {{#if isFormTable}}
            <template v-slot="{height}">
              <div class="pinel">
                <div class="pinel-title">
                  <span>单据明细</span>
                  <div class="actions">
                    <el-button type="primary" icon="el-icon-plus" @click="add"></el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="formTableDel"></el-button>
                  </div>
                </div>
                <div class="pinel-content">
                  <el-table class="common-table" border :data="formData.{{field}}" @selection-change="selectionChange" :height="height">
                    <el-table-column type="selection" width="40"></el-table-column>
                    <el-table-column label="字段1" prop="field1" min-width="200"></el-table-column>
                    <el-table-column label="字段2" prop="field2" min-width="200">
                      <template v-slot="{ row, $index }">
                        <el-form-item :prop="`{{field}}.${$index}.field2`" :rules="{}">
                          <t-input v-model="row.field2" placeholder="请输入"/>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </template>
          {{/if}}
        </component>
      </div>
    </template>
  </table-pinel>
</template>

<script>
  import quertMixin from "@ultra/share/mixins/quertMixin";
  import tableSelectionMixin from "@ultra/share/mixins/tableSelectionMixin";
  import {listToOptions, objToOptions} from "@ultra/share/utils/util";
  import {mapMutations, mapState} from "vuex";
  import {cloneDeep} from 'lodash'
  import {teamPage, teamDelete, teamAdd, teamUpdate} from "@ultra/share/api/common/data/team";

  export default {
    name: "{{capitalizeFirstLetter name}}",
    mixins: [quertMixin, tableSelectionMixin],
    data() {
      return {
        // 查询参数
        searchParams: {
          pageSize: 20,
          userName: null,
          date: []
        },
        type: "",
        title: "",
        // 表单参数
        formData: {
          supplierCode: null,
          supplierName: null,
          totalMoney: null,
        },
        cacheFormData: {},
        {{#if isFormTable}}
          selections: [],
        {{/if}}
      };
    },
    computed: {
      ...mapState("maps", ["inputTypeMap"]),
      searchConfig() {
        return {
          formItemConfig: [
            {
              label: "用户昵称",
              prop: "nickName",
              component: this.inputTypeMap['input'],
            },
            {
              label: '检验类别',
              prop: 'inspectionType',
              component: this.inputTypeMap['select'],
              options: objToOptions({1: '1', 2: '2'})
            },
            {
              label: '创建时间',
              prop: 'date',
              component: 'el-date-picker',
              type: 'daterange',
              rangeSeparator: '至',
              startPlaceholder: '开始日期',
              endPlaceholder: '结束日期',
              onChange: (e) => {
                this.setDate(e, ['date', 'startDate', 'endDate']);
              }
            }
          ],
        };
      },
      api() {
        return {0: teamAdd, 1: teamUpdate}[this.type] || teamAdd;
      },
      rules() {
        return {
          userName: [
            {
              required: true, message: "用户账号不能为空", trigger: "blur"
            }
          ],
          nickName: [
            {
              required: true, message: "用户昵称不能为空", trigger: "blur"
            }
          ],
        };
      },
      formItemConfig() {
        return [
          {
            span: 24,
            label: "部门ID",
            prop: "deptId",
            component: this.inputTypeMap['input'],
          },
          {
            span: 24,
            label: "用户类型",
            prop: "userType",
            component: this.inputTypeMap['select'],
          },
          {
            span: 12,
            label: '检验方式',
            prop: 'inspectionMethod',
            component: this.inputTypeMap['select'],
            // 1-工具 2-目视
            options: objToOptions({1: '工具', 2: '目视'})
          },
          {
            span: 24,
            label: '附件',
            prop: 'attachmentId',
            component: this.inputTypeMap['upload'],
            tips: '支持扩展名：.rar .zip .doc .docx .pdf .jpg...',
            multiple: false
          },
          {
            span: 24,
            label: '备注',
            prop: 'remark',
            component: this.inputTypeMap['input'],
            type: 'textarea',
            rows: 4
          }
        ];
      },
    },
    methods: {
      //  新增/修改/删除 操作成功事件回调
      onSuccess() {
        this.search();
      },
      /** 查询用户信息列表 */
      query(params) {
        teamPage(params).then((res) => {
          if (res.success) {
            this.tableData = res.result.records;
            this.pageSearchParams.total = res.result.total;
          }
        });
      },
      /** 新增按钮操作 */
      create() {
        this.initFormData(0);
        this.$refs.modalEdit.show();
      },
      /** 修改按钮操作 */
      edit(row) {
        this.initFormData(1, row);
        this.$refs.modalEdit.show();
      },
      /** 查看按钮操作 */
      detail(row) {
        this.initFormData(2, row);
        this.$refs.modalEdit.show();
      },
      // 初始化表格字段
      initFormData(type, row) {
        this.type = type;
        if (type === 1 || type === 2) {
          this.title = type === 1 ? "编辑{{title}}" : "查看{{title}}";
          this.formData = {
            id: null,
            ...this.cacheFormData
          };
          Object.keys(this.formData).forEach(key => {
            this.formData[key] = row[key]
          })
        } else {
          this.title = "添加{{title}}";
          this.formData = cloneDeep(this.cacheFormData)
        }
      },
      /** 删除按钮操作 */
      del(row) {
        this.$confirm("删除后无法恢复, 是否确认?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          teamDelete(row.id).then((res) => {
            if (res.success) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.onSuccess();
            }
          });
        });
      },
      // 表单弹窗内的表格操作  todo
      {{#if isFormTable}}
        add() {
          this.$refs.deviceModal.show();
        },
        setValue(val) {
          if (val.length) {
            val.forEach((item) => {
              if (this.formData.{{field}}.
              findIndex((i) => i.deviceCode === item.deviceCode) === -1
            )
              {
                this.formData
              .{{field}}.
                push(item);
              }
            });
          }
        },
        selectionChange(val) {
          this.selections = val;
        },
        formTableDel() {
          this.selections.forEach((item) => {
            const index = this.formData
          .{{field}}.
            findIndex((i) => i.deviceCode === item.deviceCode);
            this.formData
          .{{field}}.
            splice(index, 1);
          });
        },
      {{/if}}
      openDialog(modal) {
        return () => {
          this.$refs[modal].show();
        };
      },
      /**
       * @param: e 选中行
       * @param: nameKey Array 显示名称【0 表单key 1 item key】
       * @param: valueKey Array 显示值【0 表单key 1 item key】
       * @Description: 弹窗选择
       */
      handleClickFormSelected(e, ...args) {
        for (let i = 0; i < args.length; i++) {
          const nameKey = args[i][0];
          const valueKey = args[i][1];
          if (e) {
            this.formData[nameKey] = e[valueKey];
          } else {
            this.formData[nameKey] = undefined;
          }
        }
      },
      /** 导出按钮操作 */
      // handleExport() {
      //   exportUser(this.searchParams).then(() => {
      //     this.$message.success("导出成功");
      //   }).catch((r) => {
      //     console.log(r);
      //     this.$message.error("导出失败");
      //   })
      // }
    },
    created() {
      this.cacheFormData = cloneDeep(this.formData)
    }
  };
</script>
